package org.dce.screencapturer.editors;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

import org.dce.screencapturer.objects.ShapeObject;

@SuppressWarnings("serial")
public abstract class Editor extends JDialog {

	protected ShapeObject editedObject;

	private final JPanel buttons = new JPanel(new FlowLayout(FlowLayout.RIGHT));
	
	public Editor(ShapeObject editedObject,String title){
		super(JOptionPane.getFrameForComponent(editedObject),title,true);
		
		this.editedObject = editedObject;
		
		setLayout(new BorderLayout());
		
		add(buttons,BorderLayout.SOUTH);
		
		JButton ok = new JButton("Ok");
		ok.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				onAccept();
			}
		});
		buttons.add(ok);
		
		JButton cancel = new JButton("Cancel");
		cancel.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				onCancel();
			}
		});
		buttons.add(cancel);
		
		setSize(640,480);
		
	}
	
	protected void addButton(JButton button){
		// Insert other buttons before ok/cancel
		buttons.add(button,buttons.getComponentCount()-2);
	}
	
	public void showEditor(){
		Dimension size = getToolkit().getScreenSize();
		
		setLocation((size.width-getWidth())/2,(size.height-getHeight())/2);
		
		readFromObject();
		
		setVisible(true);
	}
	
	protected abstract void readFromObject();
	
	protected abstract void writeToObject();
	
	private void onAccept(){
		writeToObject();
		setVisible(false);
	}	
	private void onCancel(){
		setVisible(false);
	}
}
